var salt = sessionStorage.getItem('usersalt');

layui.use(['form', 'layer'], function() {
  var form = layui.form,
      layer = parent.layer === undefined ? layui.layer : top.layer,
      $ = layui.jquery;

  if(!sessionStorage.getItem('username')) {
    layer.msg('请先登录');
    setTimeout("top.location.href='../../../index.html'", 1000);
  }
});

/*------------单位节点树.start------------*/
function showUnitTree() {
  $('#applyUnitTree').show();
}

var company;

function getAllCompany() {
  $.ajax({
    url: url + 'baseEnt/getAllEnt',
    dataType: 'json',
    async: false,
    type: "POST",
    data: {},
    success: function(data) {
      $('#applyUnitTree').empty();
      if(data.code == 0) {
        company = data.data;
      }
    },
    error: function(error) {
      console.log("获取失败");
    }
  });
}
getAllCompany();

var setting = {
  data: {
    simpleData: {
      enable: true
    }
  },
  check: {
    enable: true,
    chkStyle: "radio", //单选框
    radioType: "all" //对所有节点设置单选
  },
  callback: {
    onCheck: zTreeOnCheck
  }
};

$.fn.zTree.init($("#applyUnitTree"), setting, company);

function zTreeOnCheck(event, treeId, treeNode) {
  var checked = treeNode.checked;
  if(checked) {
    $('#applyUnit').val(treeNode.name);
  } else {
    $('#applyUnit').val("");
  }
  $('#applyUnitTree').hide();
};

function getTreeVal() {
  var unitTreeVal = [];
  var treeObj = $.fn.zTree.getZTreeObj("applyUnitTree");
  var nodes = treeObj.getCheckedNodes(true);
  for(var i = 0; i < nodes.length; i++) {
    unitTreeVal.push(nodes[i].id); //获取选中节点的值
  }
  return unitTreeVal;
}
/*------------单位节点树.end------------*/

/*-------------新增安全检查表.start-------------*/
//判断检查项目填写是否正确
function judgeItemArr() {
  for(var i = 0; i < itemArr.length; i++) {
    if(itemArr[i].isShow == 1) {
      var name = itemArr[i].name;
      var emptyNum = 0; //检查内容、评分细则都为空的数量
      var notEmptyNum = 0; //检查内容、评分细则都不为空的数量
      for(var j = 0; j < itemArr[i].list.length; j++) {
        if(itemArr[i].list[j].isShow == 1) {
          if(itemArr[i].list[j].content != "" && itemArr[i].list[j].rule == "") {
            return false;
          } else if(itemArr[i].list[j].content == "" && itemArr[i].list[j].rule != "") {
            return false;
          } else if(itemArr[i].list[j].content == "" && itemArr[i].list[j].rule == "") {
            ++emptyNum;
          } else {
            ++notEmptyNum;
          }
        }
      }
      if(name == "" && notEmptyNum > 0) {
        return false;
      } else if(name != "" && emptyNum == itemArr[i].list.length) {
        return false;
      } else if(name == "" && i == 0) {
        return false;
      }
    }
  }
  return true;
}

function addSecurityCheck() {
  checkName = $.trim($("#checkName").val()); //检查表名称
  if(checkName == "") {
    layer.msg('请填写检查表名称');
    return;
  }
  var applyUnitId = getTreeVal().toString(); //适用单位id
  if(applyUnitId == 0 || applyUnitId == "") {
    if(checkId != false) { //编辑
      applyUnitId = editCompanyId;
    } else {
      layer.msg('请选择适用单位');
      return;
    }
  }
  var type = $("#type").val(); //检查类别
  var itemBool = judgeItemArr();
  if(!itemBool) {
    layer.msg('请填写完整检查项目');
    return;
  }
  if(checkId == false) { //新增时
    checkId = "";
  }
  $.ajax({
    url: url + 'checkInfo/add',
    dataType: 'json',
    async: false,
    type: "POST",
    data: {
      Token: salt,
      checkId: checkId,
      checkName: checkName,
      applyUnitId: applyUnitId,
      type: type,
      itemJsonStr: JSON.stringify(itemArr)
    },
    success: function(data) {
      if(data.code == 0) {
        var str = "新增安全检查表提交成功！";
        if(checkId != "") {
          str = "修改安全检查表提交成功！";
        }
        layer.confirm(str, {
          btn: ['确定'] //按钮
        }, function() {
          location.href = "../check-list/check-list.html";
        }, function() {});
      } else {
        layer.msg(data.msg);
      }
    },
    error: function(error) {
      console.log("获取失败");
    }
  });
}
/*-------------新增安全检查表.end-------------*/

/*-------------元素位置.start-------------*/
function setPosition() {
  var textareaHeight = $("textarea").height();
  $(".ctddel").height(textareaHeight + 2); //2为textarea线的高度
  $(".ctdadd").height(textareaHeight + 2);
  $(".cti-add").css("margin-top", textareaHeight - 16);
}
/*-------------元素位置.end-------------*/

/*-------------检查项目显示、隐藏、添加、删除.start-------------*/
var itemArr = [{
  isShow: 1,
  id: "",
  name: "",
  list: [{
    isShow: 1,
    content: "",
    rule: ""
  }]
}];

//页面检查项目框显示
function initItemShow() {
  var tbodyHtml = "";
  for(var i = 0; i < itemArr.length; i++) {
    if(itemArr[i].isShow == 1) {
      var rightTab = 1; //右侧添加检查项目按钮合并行数
      var contentHtml = ""; //检查项目内容html
      //内容框list
      for(var j = 0; j < itemArr[i].list.length; j++) {
        if(itemArr[i].list[j].isShow == 1) {
					/*-------------检查项目内容.start-------------*/
          contentHtml += "<tr id=\"item-content-" + i + "-" + j + "\">" +
              "<td>" +
              "</td>" +
              "<td style=\"padding-right: 0px;\">" +
              "<div class=\"layui-col-md12 ctd ctd1 sectd\">" +
              "<div class=\"layui-col-md12 ctdd\">" +
              "<div class=\"layui-col-md1 ctdlb\"><label>检查内容</label></div>" +
              "<textarea rows=\"3\" class=\"layui-col-md11 cttara\" id=\"item-content-" + i + "-" + j + "-textarea-1\"" +
              "onchange=\"setItemValue('item-content-" + i + "-" + j + "-textarea-1', " + i + ", 'textarea', " + j + ", 1)\">" + itemArr[i].list[j].content + "</textarea>" +
              "</div>" +
              "<div class=\"layui-col-md12\">" +
              "<div class=\"layui-col-md1 ctdlb\"><label>评分细则</label></div>" +
              "<textarea rows=\"3\" class=\"layui-col-md11 cttara\" id=\"item-content-" + i + "-" + j + "-textarea-2\"" +
              "onchange=\"setItemValue('item-content-" + i + "-" + j + "-textarea-2', " + i + ", 'textarea', " + j + ", 2)\">" + itemArr[i].list[j].rule + "</textarea>" +
              "</div>" +
              "</div>" +
              "</td>" +
              "<td colspan=\"2\" style=\"padding-left: 0px;padding-right: 0px;\">" +
              "<div class=\"layui-col-md12 ctd ctd2\">" +
              "<div class=\"ctdd ctddel\">" +
              "<i class=\"cti cti-del\" onclick=\"delContent(" + i + "," + j + ")\"></i>" +
              "</div>" +
              "<div class=\"ctdadd\">" +
              "<i class=\"cti cti-add\" onclick=\"addContent(" + i + ")\"></i>" +
              "</div>" +
              "</div>" +
              "</td>" +
              "</tr>";
					/*-------------检查项目内容.end-------------*/
          //按钮合并行数+1
          ++rightTab;
        }
      }

			/*-------------检查项目.start-------------*/
      tbodyHtml += "<tr id=\"item-" + i + "\">" +
          "<td class=\"layui-bg-green\">" +
          "<div class=\"layui-input-inline ftdl\">" +
          "<label class=\"item-nav\">检查项目</label>" +
          "</div>" +
          "</td>" +
          "<td colspan=\"3\" class=\"layui-bg-green\">" +
          "</td>" +
          "<td class=\"delIcon\" onclick=\"delItem(" + i + ")\">" +
          "</td>" +
          "</tr>";
      tbodyHtml += "<tr id=\"item-title-" + i + "\">" +
          "<td>" +
          "<div class=\"layui-input-inline ftdl\">" +
          "<label class=\"fowei\">检查项目</label>" +
          "</div>" +
          "</td>" +
          "<td style=\"padding-right: 0px;\">" +
          "<input type=\"text\" class=\"layui-input\" id=\"item-name-" + i + "\" value=\"" + itemArr[i].name + "\" placeholder=\"输入检查项目名称\" onchange=\"setItemValue('item-name-" + i + "', " + i + ", 'name', null, null)\"/>" +
          "</td>" +
          "<td colspan=\"2\">" +
          "</td>" +
          "<td rowspan=\"" + rightTab + "\" style=\"vertical-align: middle; padding:0px 9px;\" id=\"item-title-" + i + "-rightBtn\">" +
          "<div class=\"rctd\" onclick=\"addItem()\">" +
          "<div class=\"rctd-add\"></div>" +
          "<p>增</p><p>加</p><p>检</p>" +
          "<p>查</p><p>项</p><p>目</p>" +
          "</div>" +
          "</td>" +
          "</tr>";
      tbodyHtml += contentHtml;
			/*-------------检查项目.end-------------*/
    }
  }
	/*-------------提交按钮.end-------------*/
  tbodyHtml += "<tr>" +
      "<td colspan=\"5\" style=\"text-align: center;\"><button type=\"button\" style=\"width: 100px;font-size: 16px;margin-top: 20px;\" class=\"layui-btn layui-btn-danger\" onclick=\"addSecurityCheck()\">提&nbsp;交</button></td>" +
      "</tr>";
	/*-------------提交按钮.end-------------*/
  // $("#addTable").html(tbodyHtml);
  setPosition();
}

//项目内容赋值
function setItemValue(id, itemOrder, type, listOrder, textType) {
  if(type == "name") {
    itemArr[itemOrder].name = $("#" + id).val();
  } else {
    if(textType == 1) {
      itemArr[itemOrder].list[listOrder].content = $("#" + id).val();
    } else {
      itemArr[itemOrder].list[listOrder].rule = $("#" + id).val();
    }
  }
}

//获取显示的检查项目数量
function getShowItemNum() {
  var showNum = 0;
  for(var i = 0; i < itemArr.length; i++) {
    if(itemArr[i].isShow == 1) {
      ++showNum;
    }
  }
  return showNum;
}

//增加检查项目
function addItem() {
  var showNum = getShowItemNum();
  itemArr[showNum] = {
    isShow: 1,
    id: "",
    name: "",
    list: [{
      isShow: 1,
      content: "",
      rule: ""
    }]
  };
  initItemShow();
}

//删除检查项目
function delItem(index) {
  var showNum = getShowItemNum();
  if(showNum == 1) {
    return;
  }
  for(var i = 0; i < itemArr.length; i++) {
    var maxIndex = itemArr.length - 1;
    if(i >= index && i < maxIndex) {
      itemArr[i] = itemArr[i + 1];
    }
  }
  itemArr.pop();
  initItemShow();
}

//获取显示的检查内容数量
function getShowContent(itemOrder) {
  var showNum = 0;
  for(var i = 0; i < itemArr[itemOrder].list.length; i++) {
    if(itemArr[itemOrder].list[i].isShow == 1) {
      ++showNum;
    }
  }
  return showNum;
}

//删除内容框
function delContent(itemOrder, listOrder) {
  var showNum = getShowContent(itemOrder);
  if(showNum == 1) {
    return;
  }
  for(var i = 0; i < itemArr[itemOrder].list.length; i++) {
    var maxIndex = itemArr[itemOrder].list.length - 1;
    if(i >= listOrder && i < maxIndex) {
      itemArr[itemOrder].list[i] = itemArr[itemOrder].list[i + 1];
    }
  }
  itemArr[itemOrder].list.pop();
  initItemShow();
}

//增加内容框
function addContent(itemOrder) {
  var showNum = getShowContent(itemOrder);
  itemArr[itemOrder].list[showNum] = {
    isShow: 1,
    content: "",
    rule: ""
  };
  initItemShow();
}
/*-------------检查项目显示、隐藏、添加、删除.end-------------*/

/*-------------编辑获取值.start-------------*/
var checkId = getQueryVariable("id");
var editCompanyId;
if(checkId != false) {
  $("#pageTitle").html("编辑风险分级清单");
} else {
  $("#pageTitle").html("新增风险分级清单");
  //新增初始化
  initItemShow();
}

function initEditItem(checkInfo) {

}

	//导出
	$(".export_btn").click(function() {
		
			$.post(url + 'risk/exportInfo', {
				Token: salt,
				id: checkId
			}, function(result) {
				window.open(url + "file" + result.data);
			});
		
	});

var riskbm
//选中框变色
function addriskbm(valtext) {

}
